package ynu.javanewstudy.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import ynu.javanewstudy.pojo.Result;
import com.alibaba.fastjson.JSONObject;
import ynu.javanewstudy.utils.AliOssUtil;
import ynu.javanewstudy.utils.HttpClientUtil;

import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

@RestController
@Slf4j
@RequestMapping("/common")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;

    @PostMapping("/predictImage")
    public Result predictImage(@RequestParam("file") MultipartFile file) {
        log.info("模型预测图片:{}", file.getOriginalFilename());

        try {
            // 将文件上传到OSS
            String upload = aliOssUtil.upload(file.getBytes(), file.getOriginalFilename());

            // 将文件路径传递给Python后端进行模型预测
            String pythonBackendUrl = "http://localhost:5000/predict"; // 替换为你的Python后端URL
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("filePath", upload);  // 传递OSS文件路径给Python后端

            // 调用Python后端接口
            String response = HttpClientUtil.doPost(pythonBackendUrl, paramMap);

            log.info("Python后端返回结果: {}", response);

            // 解析返回的JSON
            JSONObject jsonResponse = JSONObject.parseObject(response);
            if (jsonResponse.containsKey("error")) {
                return Result.error(jsonResponse.getString("error"));
            }

            String predictedImageBase64 = jsonResponse.getString("predictedImage");

            // 将Base64编码的字符串解码为字节数组
            byte[] imageBytes = Base64.getDecoder().decode(predictedImageBase64);

            // 将预测后的图片上传到OSS
            String ossUrl = aliOssUtil.upload(imageBytes, "predicted_image.png");

            // 返回预测后的图片的OSS URL
            return Result.success(ossUrl);
        } catch (IOException e) {
            log.error("图片预测失败：{}", e);
            return Result.error("图片预测失败");
        }
    }

}
